package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;

import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加分类
     *
     * @param category
     * @param session
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category, HttpSession session) {
        //获取已登录的员工
        Long empId = (Long) session.getAttribute("employee");
        category.setUpdateTime(LocalDateTime.now()); //更新时间
        category.setUpdateUser(empId);   //修改人
        category.setCreateUser(empId);  //创建人
        category.setCreateTime(LocalDateTime.now());//创建时间
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(Integer page, Integer pageSize) {
        Page<Category> pageInfo = categoryService.findByPage(page, pageSize);
        return R.success(pageInfo);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.removeById(id);
        return R.success("分类信息删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category, HttpSession session) {
        Long empId = (Long) session.getAttribute("employee");
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(empId);
        categoryService.updateById(category);
        return R.success("修改分类信息成功");

    }


    @GetMapping("/list")
    public R<List<Category>> List(Integer type) {
        List<Category> categoryList = categoryService.findAll(type);
        return R.success(categoryList);
    }
}
